package lvm

import (
	"context"
	"fmt"
)

// LVExtend 逻辑卷容量增加
func LVExtend(ctx context.Context, vgName, lvName string, newSizeM int64) (lv *LogicalVolume, err error) {
	lv = getLV(ctx, vgName, lvName)
	if lv == nil {
		err = ErrNotFound
		return
	}

	vg := getVG(ctx, lv.VGName)
	if vg == nil {
		err = ErrNotFound
		return
	}

	// 只能增加
	if newSizeM*1000*1000 < lv.Size {
		err = ErrCanNotReduce
		return
	}

	if vg.FreeSize < (newSizeM*1000*1000 - lv.Size) {
		err = ErrNoEnoughSpace
		return
	}
	// 如果两次大小一致，跳过，并且返回成功
	if newSizeM*1000*1000 > lv.Size {
		_, err = execCommand(ctx, "lvextend", "--size", fmt.Sprintf("%dm", newSizeM), lv.Path)
		if err != nil {
			return
		}
	}
	lv = getLV(ctx, vgName, lvName)
	if lv == nil {
		err = ErrCommand
	}
	return
}
